package com.seabook.calparser.main;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.htmlparser.Parser;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.seabook.calparser.pojo.CalParserConfig;
import com.seabook.calparser.pojo.CalReport;
import com.seabook.calparser.util.CalParser;
import com.seabook.calparser.util.ParserBuilder;
import com.seabook.calparser.util.URIBuilder;

public class CalReportMailer extends AbstractMailSender {
	private long oneDay = 60l * 60l* 24l * 1000l;
	
	public void sendMessage(final CalParserConfig config) throws MessagingException {
		System.out.println("Mail Send Started ... ");
		
		MimeMessagePreparator preparator = new MimeMessagePreparator() {

			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
				message.setSubject(subject);
	            message.setTo(tos);
	            message.setFrom(from);
	            
	            resetDateInConfig(config);
	            System.out.println("Send Date: " + config.getWhen());
	            String uri = URIBuilder.buildURL(config);
	            System.out.println("Request Uri: " + uri);
	            Parser parser = ParserBuilder.buildParser(uri);
	            System.out.println("Cal Parser start to parse the cal logs ...");
	            List<CalReport> calReportList = CalParser.parseCalLogs(parser);
	            System.out.println("Cal Parser finished.");
	            Map model = new HashMap();
	            model.put("calReportList", calReportList);
	            model.put("config", config);
	            String text = VelocityEngineUtils.mergeTemplateIntoString(
	               velocityEngine, "/com/seabook/calparser/etc/calTemplate.vm", model);
	            message.setText(text, true);
			}

		};
		sender.send(preparator);
		System.out.println("Mail Send finished.");
	}

	private void resetDateInConfig(CalParserConfig config) {
		String currDate = config.getWhen();
		//2010-02-18_00
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm");
		Date date = null;
		try {
			date = sdf.parse(currDate);
			date.setTime(date.getTime() + oneDay);
			config.setWhen(sdf.format(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	

}
